// 搭建自己web服务器，然后把 home 目录搭建起来，至少要实现静态文件的加载展示
let http = require("http");
let fs = require("fs");
let serve = http.createServer();
serve.on('request', function (req, res) {
    let url = req.url;
    //lastIndexOf()==-1就是不存在
    if (url.lastIndexOf('.') > -1) {
        console.log(url);
        let path = '.' + url;
        readFilePromise(path,res);
    }else{
        res.end()
    }
})

let promise = function(filename){
    return new Promise(function(resolve,reject){
        fs.exists(filename,function(result){
            if(!result){
                filename = './home/demo.html';
            }
            fs.readFile(filename,function(err,data){
                resolve(data);
            })
        })
    })
}

async function readFilePromise(filename,res){
    let data = await promise(filename);
    res.write(data);
    res.end();
}

serve.listen(3000, function () {
    console.log("服务已启动http://127.0.0.1:3000");
})